<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Auth
{
	private $_CI;

    public function __construct()
    {
		$this->_CI = & get_instance();

		$this->_CI->load->model('user_m');
        $this->_CI->load->model('authGroup_m');
        $this->_CI->load->model('authRule_m');
        $this->_CI->load->model('groupAcess_m');
		log_message('debug', "FOX: Authentication library Class Initialized");

    }
	
	public function user_logout(){
		$uid=$this->_CI->session->userdata('user_id');
		$this->_CI->user_m->del_user_key_by_user_id($uid);
		$this->_CI->session->unset_userdata('user_id');
		setcookie('loveme', '', time() - 3600, '/', '', false, true);
		$this->_CI->session->sess_destroy();
		if(isMobile()){
			redirect('login');
		}else{
			redirect('user/login/');
		}
		
	}
	//用户登陆
	public function is_login(){
		$uid=$this->_CI->session->userdata('user_id');
		if(!$uid){
			return false;
		}else{
			return true;
		}
	}
	//超级管理员权限，整站权限
	public function is_super_admin()
	{
		$uid=$this->_CI->session->userdata('user_id');
		$auth_user = $this->_CI->user_m->get_user_by_user_id($uid);
        return ($this->is_login() && $auth_user['user_group'] == 1)? TRUE : FALSE;
	}
	//管理员权限
	public function is_admin()
	{
		$uid=$this->_CI->session->userdata('user_id');
		$auth_user = $this->_CI->user_m->get_user_by_user_id($uid);
        return ($this->is_login() && $auth_user['user_group']==2)? TRUE : FALSE;
	}
	
	//商家权限
	public function is_bumen()
	{
		$uid=$this->_CI->session->userdata('user_id');
		$auth_user = $this->_CI->user_m->get_user_by_user_id($uid);
        return ($this->is_login() && ($auth_user['user_group']==3))? TRUE : FALSE;
	}
    // 代理商
    public function is_agent()
    {
        $uid=$this->_CI->session->userdata('user_id');
        $auth_user = $this->_CI->user_m->get_user_by_user_id($uid);
        return ($this->is_login() && ($auth_user['user_group']==5))? TRUE : FALSE;
    }
	
	//普通用户权限
	public function is_members()
	{
		$uid=$this->_CI->session->userdata('user_id');
		$auth_user = $this->_CI->user_m->get_user_by_user_id($uid);
        return ($this->is_login() && $auth_user['user_group']<10)? TRUE : FALSE;
	}

    /**
     * 检查权限
     * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param uid  int           认证用户的id
     * @param string mode        执行check的模式
     * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check($name, $uid, $type=1, $mode='url', $relation='or') {
        $authList = $this->getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存验证通过的规则名
        if ($mode=='url') {
            $REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
        }
        foreach ( $authList as $auth ) {
            $query = preg_replace('/^.+\?/U','',$auth);
            if ($mode=='url' && $query!=$auth ) {
                parse_str($query,$param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST,$param);
                $auth = preg_replace('/\?.*$/U','',$auth);
                if ( in_array($auth,$name) && $intersect==$param ) {  //如果节点相符且url参数满足
                    $list[] = $auth ;
                }
            }else if (in_array($auth , $name)){
                $list[] = $auth ;
            }
        }
        if ($relation == 'or' and !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation == 'and' and empty($diff)) {
            return true;
        }
        return false;
    }

    /**
     * 根据用户id获取用户组,返回值为数组
     * @param  uid int     用户id
     * @return array       用户所属的用户组 array(
     *     array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *     ...)
     */
    public function getGroups($uid) {
        static $groups = array();
        if (isset($groups[$uid])){
            return $groups[$uid];
        }
        $user_groups = $this->_CI->groupAcess_m->get_groups_by_uid($uid);
        $groups=$user_groups?:array();
        return $groups;
    }

    /**
     * 获得权限列表
     * @param integer $uid  用户id
     * @param integer $type
     */
    protected function getAuthList($uid,$type) {
        static $_authList = array(); //保存用户验证通过的权限列表
        $t = implode(',',(array)$type);
        if (isset($_authList[$uid.$t])) {
            return $_authList[$uid.$t];
        }
        //读取用户所属用户组
        $groups = $this->getGroups($uid);
        $ids = $groups[0]["rules"];
        if (empty($ids)) {
            $_authList[$uid.$t] = array();
            return array();
        }
        $map = "id in ($ids) AND type = $type AND status = 1";
        //读取用户组所有权限规则
        $rules = $this->_CI->authRule_m->get_rules_available($map);
        //循环规则，判断结果。
        $authList = array();   //
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) { //根据condition进行验证
                $user[$uid] = $this->user_m->get_user_by_user_id($uid);

                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                //dump($command);//debug
                @(eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid.$t] = $authList;
        return array_unique($authList);
    }

	
}
